<template>
    <div id="home" class="upload">
        <div class="uploadContain">
            <div class="upload-demo">
                <!-- <div class="uploadBtn">
                    <el-button @click="uploadWay = 'wj'; uploadType = 'rb'" :type="uploadWay == 'wj' ? 'primary' : ''" round
                        size="large" style="width: 100px;">文件上传</el-button>
                    <el-button @click="uploadWay = 'sg'; uploadType = 'rb'" :type="uploadWay == 'sg' ? 'primary' : ''" round
                        size="large" style="width: 100px;">手工填报</el-button>
                </div> -->
                <div class="filter">
                    <div class="uploadBtn" v-if="uploadWay == 'wj'">
                        <el-select
                            v-model="uploadType"
                            class="m-2"
                            placeholder="请选择上传类型"
                            size="large"
                            style="width: 140px"
                        >
                            <el-option
                                v-for="item in uploadTypeList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </div>
                    <div
                        class="uploadBtn"
                        v-if="
                            (uploadType == 'rb' ||
                                uploadType == 'yb' ||
                                uploadType == 'scsj') &&
                            localTypeUnit == 1
                        "
                    >
                        <el-select
                            v-model="typeUnit"
                            class="m-2"
                            placeholder="请选择上传单位"
                            size="large"
                            style="width: 160px"
                        >
                            <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </div>
                    <div class="uploadBtn" v-if="uploadWay == 'sg'">
                        <el-date-picker
                            v-model="dateValue"
                            type="month"
                            size="large"
                            style="width: 130px"
                            :disabled-date="disabledDate"
                            @change="dateValueChange"
                        />
                    </div>
                    <div class="uploadBtn" v-if="uploadWay == 'wj'">
                        <el-button
                            @click="modelDownload(uploadType)"
                            size="large"
                            type="default"
                            style=""
                            :icon="Download"
                            >{{
                                uploadType == "rb"
                                    ? "日报"
                                    : uploadType == "yb"
                                    ? "月报"
                                    : "生产数据"
                            }}模版下载</el-button
                        >
                    </div>
                    <el-popover
                        :visible="visible"
                        placement="bottom"
                        :width="360"
                        :trigger="'hover'"
                    >
                        <el-scrollbar style="height: 400px">
                            <p><strong>强校验规则（禁止提交）：</strong></p>
                            <p>1、进水NH3-N≥进水TN，出水NH3-N≥出水TN</p>
                            <p>
                                2、进水BOD≥5天前的进水COD，出水BOD≥5天前的出水COD
                            </p>
                            <p>3、出水SV30≥100</p>
                            <p>4、粪大肠菌群采样日期需比日报日期早2天</p>
                            <p><strong>提示规则（可选择提交）：</strong></p>
                            <p>1、水温≤5或≥40</p>
                            <p>2、进出水PH≤6或≥9</p>
                            <p>3、出水SS≥10</p>
                            <p>4、城北厂出水COD≥50，其他厂出水COD≥30</p>
                            <p>5、城北厂、城东厂出水BOD≥10，其他厂出水BOD≥6</p>
                            <p>6、进水BOD/5天前的COD的比值≤0.2或≥0.8</p>
                            <p>7、进水COD≥500</p>
                            <p>8、城北厂出水TN≥15，其他厂出水TN≥10</p>
                            <p>9、城北厂出水NH3-N≥5，其他厂出水NH3-N≥1.5</p>
                            <p>10、城北厂出水TP≥0.5，其他厂出水TP≥0.3</p>
                            <p>11、进水TN≥45</p>
                            <p>12、进水TP≥5</p>
                            <p>13、进水NH3≥30</p>
                            <p>14、粪大肠≥1000</p>
                            <p>15、MLVSS/MLSS的比值≤0.2或≥0.8</p>
                            <p>16、SV30≥98</p>
                            <p>17、污泥含水率≤40或≥70</p>
                            <p>18、DO≥11</p>
                            <p>19、SVI≤30或≥150</p>
                            <p>20、实数校验</p>
                        </el-scrollbar>
                        <template #reference>
                            <el-button
                                class="uploadBtn"
                                size="large"
                                @click="visible = true"
                                :icon="QuestionFilled"
                                >文件上传校验规则</el-button
                            >
                        </template>
                    </el-popover>
                </div>
                <div v-if="uploadWay == 'wj'" style="width: 100%">
                    <el-upload
                        drag
                        action="#"
                        :http-request="dailyExcelImport"
                        :on-change="handleChange"
                        :file-list="fileList"
                        v-model="uploadList"
                        accept=".xlsx,.xls"
                        :on-success="
                            (res) => {
                                return handleExcelImportSuccess(res);
                            }
                        "
                    >
                        <el-icon class="el-icon--upload"
                            ><upload-filled
                        /></el-icon>
                        <div
                            class="el-upload__text"
                            style="margin-bottom: 20px"
                        >
                            上传
                            <em>{{ uploadType == "rb" ? "日报" : "月报" }}</em>
                        </div>
                        <div class="el-upload__text">
                            拖拽到这里 或者 <em>点击这里</em> 上传
                        </div>
                        <template #tip>
                            <div class="el-upload__tip" style="line-height: 2">
                                文件格式：.xlsx、.xls
                            </div>
                        </template>
                    </el-upload>
                </div>
                <div v-else>
                    <el-table
                        :data="tableData"
                        style="width: 100%"
                        border
                        :height="hHeight + 'px'"
                        size="small"
                    >
                        <el-table-column
                            prop="dateTime"
                            label="日期"
                            width="100"
                            align="center"
                        />
                        <el-table-column
                            prop="treatedWaterQuantity"
                            label="处理水量(吨)"
                            align="center"
                            v-if="waterYieldType == '1'"
                        >
                            <template #default="scope">
                                <el-input
                                    :disabled="scope.row.isNoEdit"
                                    v-model="scope.row.treatedWaterQuantity"
                                    size="small"
                                    @focus="
                                        focusFn(
                                            scope.$index,
                                            'treatedWaterQuantity'
                                        )
                                    "
                                    style="width: 100%"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="waterContent"
                            label="中水量(吨)"
                            align="center"
                            v-if="waterYieldType == '1'"
                        >
                            <template #default="scope">
                                <el-input
                                    :disabled="scope.row.isNoEdit"
                                    v-model="scope.row.waterContent"
                                    size="small"
                                    @focus="
                                        focusFn(scope.$index, 'waterContent')
                                    "
                                />
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="overflowsSewage"
                            label="外溢雨污水量(吨)"
                            align="center"
                            v-if="typeUnit == '2' && waterYieldType == '1'"
                        >
                            <template #default="scope">
                                <el-input
                                    :disabled="scope.row.isNoEdit"
                                    v-model="scope.row.overflowsSewage"
                                    size="small"
                                    @focus="
                                        focusFn(scope.$index, 'overflowsSewage')
                                    "
                                />
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="ch3cooNa"
                            label="乙酸钠(吨)"
                            align="center"
                            v-if="waterYieldType == '2'"
                        >
                            <template #default="scope">
                                <el-input
                                    :disabled="scope.row.isNoEdit"
                                    v-model="scope.row.ch3cooNa"
                                    size="small"
                                    @focus="focusFn(scope.$index, 'ch3cooNa')"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="na2C2O4"
                            label="复合碳源(吨)"
                            align="center"
                            v-if="waterYieldType == '2'"
                        >
                            <template #default="scope">
                                <el-input
                                    :disabled="scope.row.isNoEdit"
                                    v-model="scope.row.na2C2O4"
                                    size="small"
                                    @focus="focusFn(scope.$index, 'na2C2O4')"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="pac"
                            label="PAC(吨)"
                            align="center"
                            v-if="waterYieldType == '2'"
                        >
                            <template #default="scope">
                                <el-input
                                    :disabled="scope.row.isNoEdit"
                                    v-model="scope.row.pac"
                                    size="small"
                                    @focus="focusFn(scope.$index, 'pac')"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column prop="pac" label="操作" width="60">
                            <template #default="scope">
                                <!-- <el-button size="small" type="primary"
                                    @click="handleEdit(scope.$index, scope.row)">粘贴</el-button> -->
                                <div
                                    v-if="scope.row.auditStatus == '0'"
                                    style="color: #ccc"
                                >
                                    待审核中
                                </div>
                                <el-button
                                    v-else
                                    size="small"
                                    type="danger"
                                    @click="
                                        handleDelete(scope.$index, scope.row)
                                    "
                                    >清除</el-button
                                >
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="uploadBtn" style="margin-bottom: 0">
                        <el-button
                            @click="manualEntry"
                            size="large"
                            type="primary"
                            style="width: 212px; margin-top: 40rem"
                            >提交</el-button
                        >
                    </div>
                </div>
            </div>
        </div>
    </div>

    <el-dialog v-model="checkedDialogVisible" title="校验提示" width="500">
        <!-- <span>{{ checkResult }}</span> -->
        <div
            style="line-height: 1.5"
            v-html="checkResult.replace(/\n/g, '<br/>')"
        ></div>
        <div
            v-if="canSubmit"
            style="
                margin-top: 20px;
                display: flex;
                flex-direction: row;
                align-items: center;
            "
        >
            <el-icon size="18" color="#e6a23c"><WarningFilled /></el-icon
            ><span>数据有异常或超设计值，请确认是否继续提交</span>
        </div>
        <div
            v-else
            style="
                margin-top: 20px;
                display: flex;
                flex-direction: row;
                align-items: center;
            "
        >
            <el-icon size="18" color="#ff0000"><WarningFilled /></el-icon
            ><span>不合规数据，请修正后重新提交</span>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="checkedDialogVisible = false"
                    >取消</el-button
                >
                <el-button
                    v-show="canSubmit"
                    type="primary"
                    @click="continueConfirm(checkedType)"
                >
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import moment from "moment";
import { onMounted, ref, nextTick, watch, onBeforeUnmount } from "vue";
import {
    UploadFilled,
    Download,
    QuestionFilled,
    WarningFilled,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, genFileId } from "element-plus";

import Storage from "@/utils/storage.js"; // storage工具类，简单的封装
import { useRouter } from "vue-router";
import uploadHttp from "@/https/upload.js";
import dataListHttp from "@/https/dataList.js";

const props = defineProps({
    type: {
        type: String,
        default: "1",
    },
    viewType: {
        type: String,
        default: "1",
    },
    waterYieldType: {
        type: String,
        default: "1",
    },
});
const fileList = ref([]);
const uploadList = ref([]);
const uploadParam = ref({});
const localTypeUnit = ref(Storage.localGet("depId"));
const username = ref(Storage.localGet("username"));
const typeUnit = ref(Storage.localGet("depId"));
if (localTypeUnit.value == "1") {
    typeUnit.value = "2";
}
const typeUnitName = ref("");
const focusRow = ref(0);
const focusColumnName = ref("");
typeUnitName.value =
    typeUnit.value == "1"
        ? "总公司"
        : typeUnit.value == "2"
        ? "星沙厂"
        : typeUnit.value == "3"
        ? "城西厂"
        : typeUnit.value == "4"
        ? "城北厂"
        : typeUnit.value == "5"
        ? "城南厂"
        : "城东厂";
watch(typeUnit, (val) => {
    queryWater();
    typeUnitName.value =
        typeUnit.value == "1"
            ? "总公司"
            : typeUnit.value == "2"
            ? "星沙厂"
            : typeUnit.value == "3"
            ? "城西厂"
            : typeUnit.value == "4"
            ? "城北厂"
            : typeUnit.value == "5"
            ? "城南厂"
            : "城东厂";
});
let dateValue = ref(moment().format("YYYY-MM"));
const options = ref([
    // { label: '总公司', value: '1' },
    { label: "星沙厂", value: "2" },
    { label: "城西厂", value: "3" },
    { label: "城北厂", value: "4" },
    { label: "城南厂", value: "5" },
    { label: "城东厂", value: "6" },
]);
const uploadWay = ref("");
const uploadType = ref("rb");
const uploadTypeList = ref([]);
if (props.viewType == "1") {
    uploadTypeList.value = [
        { label: "月报", value: "yb" },
        { label: "生产数据", value: "scsj" },
    ];
    uploadType.value = "yb";
}
if (props.viewType == "2") {
    uploadTypeList.value = [{ label: "日报", value: "rb" }];
    uploadType.value = "rb";
}
const tableData = ref([]);

const hHeight = ref(0);
const wWidth = ref(0);
const disabledDate = ref((time) => {
    return time.getTime() > Date.now();
});

const emits = defineEmits(["submitEditEmit"]);
watch(
    () => props.type,
    (val, oldVal) => {
        console.log(val, oldVal);
        if (val == "1") {
            uploadWay.value = "wj";
        } else if (val == "2") {
            uploadWay.value = "sg";
        }
    },
    { immediate: true }
);
onMounted(() => {
    // getDepIdToName()
    queryWater();
    // manualEntry()
    nextTick(() => {
        hHeight.value = document.documentElement.clientHeight - 400;
        wWidth.value = document.documentElement.clientWidth - 340;
    });
    window.addEventListener("paste", (event) => {
        event = event || window.event;
        const clipdata = event.clipboardData || window.clipboardData;
        const value = clipdata.getData("text/plain");
        console.log(value);
        let clipboardList = value.split("\r\n");
        clipboardList.forEach((item, ind) => {
            let itemList = item.split("\t");
            clipboardList[ind] = itemList;
        });
        setTimeout(() => {
            console.log("1111", clipboardList);
            let paramsList = [];
            if (typeUnit.value == "2") {
                paramsList = [
                    "treatedWaterQuantity",
                    "waterContent",
                    "overflowsSewage",
                    "ch3cooNa",
                    "na2C2O4",
                    "pac",
                ];
            } else {
                paramsList = [
                    "treatedWaterQuantity",
                    "waterContent",
                    "ch3cooNa",
                    "na2C2O4",
                    "pac",
                ];
            }
            console.log(paramsList);
            let column = paramsList.findIndex((item) => {
                return item == focusColumnName.value;
            });
            console.log(column, paramsList);
            clipboardList.forEach((item, ind) => {
                item.forEach((n, m) => {
                    n = n.replace(/\s+/g, "");
                    n = n.replace(/(\r\n|\n|\r)/gm, "");
                    tableData.value[focusRow.value + ind][
                        paramsList[column + m]
                    ] = n;
                });
            });
        });
    });
});
const getDepIdToName = () => {
    uploadHttp.getDepIdToName().then((res) => {
        console.log(res);
    });
};
const handleChange = (file, fileList) => {
    console.log(file, fileList);
    uploadList.value = fileList;
    if (fileList.length > 1) {
        fileList.splice(0, 1);
    }
};

const checkResult = ref("");
const checkedDialogVisible = ref(false);
const canSubmit = ref(false);
const checkedType = ref("");
const confirmParams = ref({});

const dailyExcelImport = (params) => {
    console.log(params);
    confirmParams.value = params;
    if (uploadType.value == "rb" && !typeUnit.value) {
        ElMessage({
            message: "单位不能为空",
            type: "warning",
        });
        return;
    }
    console.log(params);
    if (uploadType.value == "rb") {
        // 日报上传
        let dataObj = {
            file: params.file,
            depId: typeUnit.value,
            username: username.value,
        };
        console.log(dataObj, "dataObj");
        dataListHttp.dailyCheckExcelImport(dataObj).then((res) => {
            console.log(res);
            if (res.data.code == 200) {
                uploadHttp.dailyExcelImport(dataObj).then((res) => {
                    console.log(res);
                    if (res.data.code == 200) {
                        ElMessage({
                            message: "上传成功",
                            type: "success",
                        });
                        emits("submitEditEmit");
                    } else {
                        fileList.value = [];
                        ElMessage({
                            message: "上传失败,请重新上传",
                            type: "error",
                        });
                    }
                });
            } else {
                checkedDialogVisible.value = true;
                checkResult.value = res.data.msg;
                checkedType.value = "rb";
                if (res.data.code != 500) {
                    canSubmit.value = true;
                }
            }
        });
    } else if (uploadType.value == "yb") {
        // 月报上传
        let dataObj = {
            file: params.file,
            depId: typeUnit.value,
            username: username.value,
        };
        dataListHttp.dailyCheckExcelImport(dataObj).then((res) => {
            console.log(res);
            if (res.data.code == 200) {
                uploadHttp.monthlyExcelImport(dataObj).then((res) => {
                    console.log(res);
                    if (res.data.code == 200) {
                        ElMessage({
                            message: "上传成功",
                            type: "success",
                        });
                        emits("submitEditEmit");
                    } else {
                        fileList.value = [];
                        ElMessage({
                            message: "上传失败,请重新上传",
                            type: "error",
                        });
                    }
                });
            } else {
                checkedDialogVisible.value = true;
                checkResult.value = res.data.msg;
                checkedType.value = "yb";
                if (res.data.code != 500) {
                    canSubmit.value = true;
                }
            }
        });
    } else {
        let dataObj = {
            file: params.file,
            depId: typeUnit.value,
            username: username.value,
        };
        dataListHttp.dailyCheckExcelImport(dataObj).then((res) => {
            console.log(res);
            if (res.data.code == 200) {
                uploadHttp.waterYield(dataObj).then((res) => {
                    console.log(res);
                    if (res.data.code == 200) {
                        ElMessage({
                            message: "上传成功",
                            type: "success",
                        });
                        emits("submitEditEmit");
                    } else {
                        fileList.value = [];
                        ElMessage({
                            message: "上传失败,请重新上传",
                            type: "error",
                        });
                    }
                });
            } else {
                checkedDialogVisible.value = true;
                checkResult.value = res.data.msg;
                if (res.data.code != 500) {
                    canSubmit.value = true;
                }
            }
        });
    }
};
const continueConfirm = (type) => {
    let params = confirmParams.value;
    let dataObj = {
        file: params.file,
        depId: typeUnit.value,
        username: username.value,
    };
    if (type == "rb") {
        uploadHttp.dailyExcelImport(dataObj).then((res) => {
            console.log(res);
            if (res.data.code == 200) {
                ElMessage({
                    message: "上传成功",
                    type: "success",
                });
                checkedDialogVisible.value = false;
                emits("submitEditEmit");
            } else {
                fileList.value = [];
                ElMessage({
                    message: "上传失败,请重新上传",
                    type: "error",
                });
            }
        });
    } else if (type == "yb") {
        uploadHttp.monthlyExcelImport(dataObj).then((res) => {
            console.log(res);
            if (res.data.code == 200) {
                ElMessage({
                    message: "上传成功",
                    type: "success",
                });
                checkedDialogVisible.value = false;
                emits("submitEditEmit");
            } else {
                fileList.value = [];
                ElMessage({
                    message: "上传失败,请重新上传",
                    type: "error",
                });
            }
        });
    } else {
        uploadHttp.waterYield(dataObj).then((res) => {
            console.log(res);
            if (res.data.code == 200) {
                ElMessage({
                    message: "上传成功",
                    type: "success",
                });
                checkedDialogVisible.value = false;
                emits("submitEditEmit");
            } else {
                fileList.value = [];
                ElMessage({
                    message: "上传失败,请重新上传",
                    type: "error",
                });
            }
        });
    }
};
const dateValueChange = (item) => {
    dateValue.value = item;
    console.log(moment(dateValue.value).format("YYYY-MM-DD"));
    queryWater();
};
const queryWater = () => {
    let params = {
        entryDate: moment(dateValue.value).format("YYYYMM"),
        depId: typeUnit.value,
    };
    uploadHttp.queryWater(params).then((res) => {
        console.log(res);
        res.data.data.forEach((item) => {
            // item.auditStatus = '0'
            item.dateTime = moment(item.entryDate).format("YYYY-MM-DD");
            if (
                moment(item.dateTime).valueOf() > moment().valueOf() ||
                item.auditStatus == "0"
            ) {
                item.isNoEdit = true;
            } else {
                item.isNoEdit = false;
            }
        });
        tableData.value = res.data.data;
    });
};
const manualEntry = () => {
    let confirmList = [];
    tableData.value.forEach((item) => {
        item.depId = typeUnit.value;
        if (item.auditStatus != "0") {
            confirmList.push(item);
        }
    });
    let params = {
        manualEntryDTOList: confirmList,
        username: username.value,
    };
    uploadHttp.manualEntry(params).then((res) => {
        console.log(res);
        if (res.data.code == 200) {
            ElMessage({
                message: "上传成功",
                type: "success",
            });
            queryWater();
            emits("submitEditEmit");
        } else {
            ElMessage({
                message: "上传失败,请重新上传",
                type: "error",
            });
        }
    });
};
const handleExcelImportSuccess = (res) => {
    console.log("--------", res);
};
const modelDownload = (uploadType) => {
    let http =
        uploadType == "rb"
            ? "dailyDownload"
            : uploadType == "yb"
            ? "monthlyDownload"
            : "dowmloadProduction";
    console.log(http);
    uploadHttp[http](typeUnit.value).then((response) => {
        console.log(response);
        const content = response.data;
        const blob = new Blob([content], { type: "application/ms-excel" });
        let fileName = "";
        if (uploadType == "scsj") {
            fileName = `生产数据上传模版.xls`;
        } else {
            fileName = `${typeUnitName.value}上传模版.xls`;
        }
        if ("download" in document.createElement("a")) {
            // 非IE下载
            const elink = document.createElement("a");
            elink.download = fileName;
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName);
        }
    });
};
const handleDelete = (index, row) => {
    tableData.value[index].treatedWaterQuantity = "";
    tableData.value[index].waterContent = "";
    tableData.value[index].overflowsSewage = "";
    tableData.value[index].ch3cooNa = "";
    tableData.value[index].na2C2O4 = "";
    tableData.value[index].pac = "";
};
const focusFn = (row, columnName) => {
    console.log("1111------", row, columnName);
    focusRow.value = row;
    focusColumnName.value = columnName;
};

const handleEdit = (index, row) => {
    console.log("剪切板内容:", navigator.clipboard);
    navigator.clipboard
        .read()
        .then((res) => {
            console.log("剪切板内容:", res);
            if (res) {
                let clipboardList = res.split("\r\n");
                console.log("剪切板内容:", clipboardList);
                clipboardList.forEach((item, ind) => {
                    let itemList = item.split("\t");
                    tableData.value[index + ind].treatedWaterQuantity =
                        itemList[0] || "";
                    tableData.value[index + ind].waterContent =
                        itemList[1] || "";
                    tableData.value[index + ind].overflowsSewage =
                        itemList[2] || "";
                    tableData.value[index + ind].ch3cooNa = itemList[3] || "";
                    tableData.value[index + ind].na2C2O4 = itemList[4] || "";
                    tableData.value[index + ind].pac = itemList[5] || "";
                });
            }
        })
        .catch((err) => {
            console.log("获取剪切板内容失败:", err);
        });
    // console.log(window.clipboardData)
    // document.addEventListener('paste', (event) => {
    //     event.preventDefault()
    //     console.log(1111)
    //     let paste = (event.clipboardData || window.clipboardData).getData(
    //         'text'
    //     )
    //     console.log(paste)
    // })
};
</script>
<style lang="less">
@import "@/assets/css/home.less";

.upload {
    padding-bottom: 0 !important;

    .uploadContain {
        width: 100%;

        .upload-demo {
            .filter {
                display: flex;
                flex-direction: row;
            }

            .uploadBtn {
                text-align: left;
                margin-bottom: 40rem;
                margin-right: 20rem;
            }
        }
    }
}
</style>
